var fs = require('fs')
var request = require('request')
var logger = require('../log/logger')

const requestOptions = function () {
  return {
    baseUrl: 'https://api.weitrun.com',
    method: 'POST',
    url: ''
  }
}

const errorMsg = function () {
  return {
    'code': 401,
    'msg': '响应超时，稍后再试'
  }
}

exports.common = function (req, res) {
  var options = requestOptions()
  options.url = req.originalUrl
  options.form = req.body
  // logger.info(req.originalUrl + ' params:' + JSON.stringify(req.body))
  const callback = function (error, response, data) {
    if (!error && response.statusCode === 200) {
      res.send(data)
    } else {
      logger.error(options.url)
      if (data) {
        logger.error(data)
        res.status(response.statusCode).send(data)
      } else {
        logger.error(error)
        res.status(500).send(errorMsg())
      }
    }
  }
  try {
    request(options, callback)
  } catch (e) {
    logger.error(e)
  }
}

exports.fileAgent = function (req, res) {
  var options = requestOptions()
  options.url = req.originalUrl
  var url = options.baseUrl + req.originalUrl

  var formData = {
    'file': {
      value: fs.createReadStream(req.file.path),
      options: {
        filename: req.file.originalname,
        contentType: req.file.mimetype
      }
    }
  }

  const callback = function (error, response, data) {
    fs.unlink(req.file.path, function () { })
    if (!error && response.statusCode === 200) {
      res.send(data)
    } else {
      logger.error(options.url)
      if (data) {
        logger.error(data)
        res.status(response.statusCode).send(data)
      } else {
        logger.error(error)
        res.status(404).send(errorMsg())
      }
    }
  }

  request.post({
    url: url,
    formData: formData
  }, callback)
}
